package com.dhcc.sds.base.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.dao.SplitTablesMapper;
import com.dhcc.core.modules.system.entity.SplitTablesEntity;
import com.dhcc.sds.base.dao.HistoryDataMapper;
import com.dhcc.sds.base.service.IHistoryDataService;
import com.dhcc.sds.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("historyDataService")
public class HistoryDataServiceImpl implements IHistoryDataService {
	@Autowired
	SplitTablesMapper splitTablesMapper;
	@Autowired
	HistoryDataMapper historyDataMapper;
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	double all = 1;
	Double cur = (double) 0;
	
	double allArch = 1;
	Double curArch = (double) 0;
	
	/**
	 * @Description：根据时间创建存储历史数据的历史表 转存历史数据  删除历史数据
	 * @Title: creatHistoryTable   
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void historyData(Map<String, Object> map) {
		int year = DateUtil.getNowYear()-1;//当前年份
		
		//查询需转存的历史表名称
		Wrapper<SplitTablesEntity> wrapper = new EntityWrapper<>();
		wrapper.orderBy("levels", false);
		List<SplitTablesEntity> splitTables = splitTablesMapper.selectList(wrapper);
		allArch = splitTables.size()*3;//此处乘3  创建历史表+ 转存历史表 + 删除原数据
		if(CommonUtil.isNotEmpty(splitTables)){
			//创建历史表
			for(SplitTablesEntity table : splitTables){
				String tableName = table.getTableName();
				historyDataMapper.createHistoryTable(tableName, year);
				curArch ++;
			}
			
			//转存历史数据
			//先查询时间范围内的患者ID
			String startDate = year + "-01-01 00:00:00";
			String endDate = year +"-12-31 23:59:59";
			Map<String,Object> params = new HashMap<String, Object>();
			params.put("startDate", startDate);
			params.put("endDate", endDate);
			params.put("year", year);
			for(SplitTablesEntity table : splitTables){
				String tableName = table.getTableName();//表名
				String joinField = table.getJoinField();//关联字段名
				Long parentId = table.getParentId(); // 父表

				List<SplitTablesEntity> parentTables = getLinkTables(parentId);

				params.put("tableName", tableName);
				params.put("joinField", joinField);
				params.put("parentTables", parentTables);
				historyDataMapper.insertHistoryData(params);
				curArch ++;
			}
			
			//删除主表中的历史数据
			for(SplitTablesEntity table : splitTables){
				String tableName = table.getTableName();//表名
				String joinField = table.getJoinField();//关联字段名
				Long parentId = table.getParentId(); // 父表

				List<SplitTablesEntity> parentTables = getLinkTables(parentId);

				params.put("tableName", tableName);
				params.put("joinField", joinField);
				params.put("parentTables", parentTables);
				historyDataMapper.deleteHistoryData(params);
				//整理数据文件的碎片,优化delete后的存储空间
				jdbcTemplate.execute("OPTIMIZE TABLE " + tableName);
				curArch ++;
			}
		}
	}

	/**
	 * @Description：查询是否有某年的转存表
	 * @Title: checkTableExist
	 * @param tableYear
	 * @return
	 */
	@Override
	public String checkTableExist(String tableYear) {
		// TODO Auto-generated method stub
		return historyDataMapper.checkTableExist(tableYear);
	}

	@Override
	public Map<String, Object> getManualStatisProcess() {
		Map<String, Object> state = new HashMap<String, Object>();
		if(all==0) {//没有获取到数据
			state.put("v", "100");//值
			state.put("i","none");//信息
		}else {
			if(cur<all) {//进行中
				DecimalFormat df = new DecimalFormat("0.00");
				state.put("v", df.format(cur/all*100));//值
				state.put("i","doing");//信息
			}else {
				state.put("v", "100");//值
				state.put("i","done");//信息
			}
		}
		return state;
	}

	@Override
	public Map<String, Object> archiveDataProcess() {
		Map<String, Object> state = new HashMap<String, Object>();
		if(allArch==0) {//没有获取到数据
			state.put("v", "100");//值
			state.put("i","none");//信息
		}else {
			if(curArch<allArch) {//进行中
				DecimalFormat df = new DecimalFormat("0.00");
				state.put("v", df.format(curArch/allArch*100));//值
				state.put("i","doing");//信息
			}else {
				state.put("v", "100");//值
				state.put("i","done");//信息
			}
		}
		return state;
	}

	public List<SplitTablesEntity> getLinkTables(Long parentId) {
		List<SplitTablesEntity> linkTables = new ArrayList<>();
		if (parentId == null) {
			return linkTables;
		}
		// 获取父表信息
		SplitTablesEntity parentTable = splitTablesMapper.selectById(parentId);
		linkTables.add(parentTable);
		// 递归
		linkTables.addAll(getLinkTables(parentTable.getParentId()));

		linkTables = linkTables.stream().sorted(Comparator.comparing(SplitTablesEntity::getLevels).reversed()).collect(Collectors.toList());
		return linkTables;
	}
}
